package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 菜品新增
     *
     * @param dishDTO
     * @return
     */
    @Override
    @Transactional
    public Result addDish(DishDTO dishDTO) {
        if (dishDTO.getCategoryId() == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setStatus(StatusConstant.DISABLE);
        dishMapper.insertDish(dish);
        Long dishid = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();

        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishid));
        dishFlavorMapper.insertBatch(flavors);
        String key = "dish_" + dishDTO.getCategoryId();
        cleanCache(key);

        return Result.success();
    }

    /**
     * 分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public Result page(DishPageQueryDTO dishPageQueryDTO) {
        if (dishPageQueryDTO.getPage() == null) {
            dishPageQueryDTO.setPage(1);
        }
        if (dishPageQueryDTO.getPageSize() == null) {
            dishPageQueryDTO.setPageSize(5);
        }
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<Dish> dishPage = dishMapper.pageQuery(dishPageQueryDTO);

        long total = dishPage.getTotal();
        List<Dish> dishList = dishPage.getResult();
        List<DishVO> dishVoList = new ArrayList(dishList.size());
        dishList.forEach(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            Category category = categoryMapper.getById(dishVO.getCategoryId());
            dishVO.setCategoryName(category.getName());
            dishVoList.add(dishVO);
        });
        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setRecords(dishVoList);
        return Result.success(pageResult);
    }

    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Result deleteDish(List<Long> ids) {
        if (ids == null || ids.size() == 0) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                return Result.error(MessageConstant.DISH_ON_SALE);
            }
        }
        List<Long> setmealDishIds = setmealMapper.getSetmealIdsByDishIds(ids);
        if (setmealDishIds != null && setmealDishIds.size() > 0) {
            return Result.error(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        dishMapper.deleteDish(ids);
        dishFlavorMapper.deleteDishFlavor(ids);
        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        cleanCache("dish_*");
        return Result.success();
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public Result getDishById(Long id) {
        if (id == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        Dish dish = dishMapper.getById(id);
        List<DishFlavor> flavors = dishFlavorMapper.getById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);
        return Result.success(dishVO);
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     * @return
     */
    @Transactional
    @Override
    public Result updateDish(DishDTO dishDTO) {
        //1.非空判断
        if (dishDTO.getCategoryId() == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //2.修改菜品表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateDish(dish);

        //3.删除口味关联表
        dishFlavorMapper.deleteDishFlavor(Arrays.asList(dish.getId()));
        //4.新增口味关联表
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
            }
        }
        //5.插入口味
        dishFlavorMapper.insertBatch(flavors);
        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        cleanCache("dish_*");
        //6.返回数据
        return Result.success();
    }

    /**
     * 修改菜品起售或停售
     *
     * @param status
     * @return
     */
    @Override
    @Transactional
    public Result updateDishStatus(Integer status, Long id) {
        if (id == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        if (status == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.updateDish(dish);
        if (status == StatusConstant.DISABLE) {
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            List<Long> setmealIds = setmealMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = new Setmeal();
                    setmeal.setId(setmealId);
                    setmeal.setStatus(StatusConstant.DISABLE);
                    setmealMapper.update(setmeal);
                }
            }
        }
        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        cleanCache("dish_*");
        return Result.success();
    }

    /**
     * 根据菜品id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public Result<List<Dish>> list(Long categoryId) {
        if (categoryId == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);
        List<Dish> list = dishMapper.list(dish);
        return Result.success(list);
    }

    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        String key = "dish_" + dish.getCategoryId();
        String dishVoListStr = stringRedisTemplate.opsForValue().get(key);
        List<DishVO> dishVOListForRedis = JSONArray.parseArray(dishVoListStr, DishVO.class);
        if (dishVOListForRedis != null && dishVOListForRedis.size() > 0) {
            return dishVOListForRedis;
        }


        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getById(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        stringRedisTemplate.opsForValue().set(key,JSONArray.toJSONString(dishVOList));
        return dishVOList;
    }
    /**
     * 清理缓存数据
     * @param pattern
     */
    private void cleanCache(String pattern){
        Set keys = stringRedisTemplate.keys(pattern);
        stringRedisTemplate.delete(keys);
    }
}
